package grid;

import java.net.*;
import java.io.*;

/**
 * A wrapper class of Socket which contains methods for sending and receiving
 * messages
 * 
 * @author zxn
 */
public class MyStreamSocket extends Socket {
    public Socket socket;

    private BufferedReader input;

    private PrintWriter output;

    private DataInputStream din;

    private DataOutputStream dout;

    private ObjectInputStream objin;

    private ObjectOutputStream objout;

    public MyStreamSocket(InetAddress acceptorHost, int acceptorPort)
            throws SocketException, IOException {
        socket = new Socket(acceptorHost, acceptorPort);
        setStreams();
    }

    public MyStreamSocket(Socket asocket) throws IOException {
        this.socket = asocket;
        setStreams();
    }

    private void setStreams() throws IOException {
        OutputStream outStream = socket.getOutputStream();
        // create a PrinterWriter object for character-mode output
        output = new PrintWriter(new OutputStreamWriter(outStream));
        dout = new DataOutputStream(outStream);
        objout = new ObjectOutputStream(outStream);

        // get an input stream for reading from the data socket
        InputStream inStream = socket.getInputStream();
        input = new BufferedReader(new InputStreamReader(inStream));
        din = new DataInputStream(inStream);
        objin = new ObjectInputStream(inStream);
    }

    public void sendString(String message) throws IOException {
        output.println(message);
        //The ensuing flush method call is necessary for the data to
        // be written to the socket data stream before the
        // socket is closed.
        output.flush();
    } // end sendMessage

    public String receiveString() throws IOException {
        // read a line from the data stream
        String message = input.readLine();
        return message;
    } //end receiveMessage

    public void sendBool(boolean bool) throws IOException {
        dout.writeBoolean(bool);
        dout.flush();
    }

    public boolean receiveBool() throws IOException {
        return din.readBoolean();
    }

    public void sendInt(int n) throws IOException {
        dout.writeInt(n);
        dout.flush();
    }

    public int receiveInt() throws IOException {
        return din.readInt();
    }

    public void sendDouble(double n) throws IOException {
        dout.writeDouble(n);
        dout.flush();
    }

    public double receiveDouble() throws IOException {
        return din.readDouble();
    }

    public void sendObject(Object obj) throws IOException {
        objout.writeObject(obj);
        objout.flush();
    }

    public Object receiveObject() throws IOException, ClassNotFoundException {
        return objin.readObject();
    }
} //end class
